import React, { Component } from 'react'
import moment from 'moment'
import { Table } from 'antd'

import { address } from '@/Utils/apiConfig'
import getData from '@/Utils/fecth'
import { APP_TIMESTAMP_FORMAT } from '@/Utils/CONST'
import '../index.less'

const txCloumn = [
  {
    title: '序号',
    dataIndex: 'No',
    sorter: {
      compare: (a, b) => a.No - b.No,
    },
  },
  {
    title: '交易哈希',
    dataIndex: 'tx_hash',
  },
  {
    title: '生成时间',
    dataIndex: 'timestamp',
    // eslint-disable-next-line react/display-name
    render: (text) => (
      <span>{moment(text).format(APP_TIMESTAMP_FORMAT)}</span>
    ),
    sorter: {
      compare: (a, b) => moment(a.timestamp).valueOf() - moment(b.timestamp).valueOf(),
    },
  },
]

const { monitor: { queryBlockDetail, queryTxDetail }} = address
class detailPage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      consortiumId: props.location.pathname.split('?')[0].split('/')[4],
      detailType: '',
      pageConf: {
        'block': [
          {
            id: 1,
            title: '区块信息',
            dataName: 'blockInfo',
            table: false,
            fields: [
              { label: '区块数据哈希', params: 'data_hash' },
              { label: '区块高度', params: 'height' },
              { label: '区块时间戳', params: 'timestamp' },
              { label: '交易数量', params: 'tx_number' },
            ],
          },
          {
            id: 2,
            title: '交易',
            dataName: 'txInfo',
            table: true,
          },
        ],
        'tx': [
          {
            id: 1,
            title: '交易信息',
            dataName: 'txInfo',
            table: false,
            fields: [
              { label: '交易哈希', params: 'tx_hash' },
              { label: '链码标识', params: 'name' },
              { label: '交易状态', params: 'status' },
              { label: '链码参数', params: 'args' },
              { label: '背书组织', params: 'endorser' },
            ],
          },
        ],
      },
      txInfo: null,
      blockInfo: null,

    }
  }

  componentDidMount() {
    const state = this.props.location.state || ''
    const pathname = this.props.location.pathname
    if (state && typeof state === 'object') {
      const type = state.type
      const data = state.data
      if (type === 'block') {
        const txInfo = data.transactions || []
        txInfo.length && txInfo.map((item, index) => {
          item.No = txInfo.length - index
          return item
        })
        let blockInfo = { ...data.block, ...{ tx_number: txInfo.length }}
        this.setState({
          detailType: type,
          blockInfo,
          txInfo,
        })
      } else {
        this.setState({
          detailType: type,
          txInfo: data,
        })
      }
    } else {
      const pathArr = pathname.split('/')
      const channelId = pathArr[pathArr.length - 2] // 获取通道id
      const _Id = pathArr[pathArr.length - 1] // 获取区块id获取交易id
      const type = pathArr[pathArr.length - 3] // 类型
      let detailType = ''
      if (type === 'blockDetail') {
        this.getDetail('block', channelId, _Id, queryBlockDetail)
        detailType = 'block'
      } else if (type === 'transactionsDetail') {
        this.getDetail('tx', channelId, _Id, queryTxDetail)
        detailType = 'tx'
      }
      this.setState({
        detailType,
      })
    }
  }

    getDetail = (type, channelId, _Id, api) => {
      const { consortiumId } = this.state
      let obj = null
      if (type === 'block') {
        obj = {
          blockId: _Id,
        }
      } else {
        obj = {
          txId: _Id,
        }
      }
      getData().get(api.format({ consortiumId, channelId, ...obj })).then(res => {
        if (res.status === 200) {
          if (type === 'block') {
            let blockInfo = res.data.block || null
            let txInfo = res.data.transactions || []
            txInfo.length && txInfo.map((item, index) => {
              item.No = txInfo.length - index
              return item
            })
            this.setState({
              blockInfo,
              txInfo,
            })
          } else {
            this.setState({
              txInfo: res.data,
            })
          }
        }
      })
    }

    getRender = (data, params) => {
      if (!data) return '-'
      if (params === 'timestamp') {
        return moment(data[params]).format(APP_TIMESTAMP_FORMAT) || '-'
      } else if (params === 'args') {
        let _data = (data[params] || []).map(v => v.replace(/[\u0000-\u001F]|[\u007F-\u00A0]/g, ''))
        let dom = _data.length ? _data.map((element, idx) => {
          return <span key={idx} className="arg-item">{element}</span>
        }) : '-'
        return dom
      } else {
        return data[params] === 0 ? 0 : (data[params] || '-')
      }
    }

    render() {
      const { pageConf, detailType } = this.state
      return (
        <div className="detail-page common">
          {
            pageConf[detailType] && pageConf[detailType].map(item => {
              return (
                <div key={item.id} className="detail-box">
                  <div className="detail-title">
                    {item.title}
                  </div>
                  {
                    item.table
                      ? <Table
                        rowKey="id"
                        columns={txCloumn}
                        dataSource={this.state[item.dataName]}
                      />
                      : item.fields.map(element => {
                        return (
                          <div key={element.params} className="detail-field">
                            <div className="field-label">{element.label}</div>
                            <div className="field-params">{this.getRender(this.state[item.dataName], element.params)}</div>
                          </div>
                        )
                      })
                  }
                </div>
              )
            })
          }
        </div>
      )
    }
}

export default detailPage
